<template>
  <div class="page-container home-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-header__content">
        <h1 class="page-title">欢迎使用 Database Universe</h1>
        <p class="page-description">数据库元数据管理平台</p>
      </div>
    </div>

    <!-- 统计数据卡片 -->
    <div class="stats-cards">
      <div
        v-for="item in statisticsItems"
        :key="item.key"
        class="stat-card"
        v-loading="loading"
      >
        <div class="stat-card__icon" :class="item.colorClass">
          <el-icon size="24">
            <component :is="item.icon" />
          </el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ stats[item.key] || 0 }}</div>
          <div class="stat-card__title">{{ item.title }}</div>
          <div class="stat-card__desc">{{ item.description }}</div>
        </div>
      </div>
    </div>

    <!-- 快速访问 -->
    <div class="quick-access-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <h3>快速访问</h3>
          </div>
        </template>
        <div class="quick-links">
          <router-link
            v-for="item in quickAccessItems"
            :key="item.path"
            :to="item.path"
            class="quick-link"
          >
            <el-button :type="getButtonType(item.path)" :icon="item.icon">
              {{ item.title }}
            </el-button>
          </router-link>
        </div>
      </el-card>
    </div>

    <!-- 系统概览 -->
    <div class="system-overview-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <h3>系统概览</h3>
          </div>
        </template>
        <div class="overview-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="当前用户">
              {{ authStore.currentUser?.displayName || '未知用户' }}
            </el-descriptions-item>
            <el-descriptions-item label="用户角色">
              <el-tag :type="getRoleTagType(authStore.userRole)">
                {{ getRoleLabel(authStore.userRole) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="系统版本">
              v1.0.0
            </el-descriptions-item>
            <el-descriptions-item label="最后更新">
              {{ formatDateTimeForDisplay(lastUpdate.toISOString()) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref} from 'vue'
import {MessageService} from '@/utils/message'
import {useAuthStore} from '@/stores/auth'
import statsService from '@/services/statsService'
import {getOrderedStatisticsItems} from '@/config/statisticsConfig'
import {getQuickAccessMenus} from '@/config/menuConfig'
import {formatDateTimeForDisplay} from '@/utils/date'

const authStore = useAuthStore()

// 加载状态
const loading = ref(false)

// 统计数据 - 使用Record类型更灵活
const stats = reactive<Record<string, number>>({})

// 最后更新时间
const lastUpdate = ref(new Date())

// 获取配置化的统计项
const statisticsItems = computed(() => {
  return getOrderedStatisticsItems()
})

// 获取快速访问菜单项
const quickAccessItems = computed(() => {
  return getQuickAccessMenus(authStore.userRole)
})

// 根据路径获取按钮类型
const getButtonType = (path: string): string => {
  const typeMap: Record<string, string> = {
    '/data/products': 'primary',
    '/access/users': 'success',
    '/access/permissions': 'warning',
    '/data/field-library': 'info',
    '/data/schemas': 'danger',
    '/data/tables': 'warning',
    '/data/dictionaries': 'info'
  }
  return typeMap[path] || 'primary'
}

// 获取用户角色标签类型
const getRoleTagType = (role: string | null) => {
  const roleTypes: Record<string, string> = {
    'SUPER_ADMIN': 'danger',
    'ADMIN': 'warning',
    'DEVELOPER': 'primary',
    'VIEWER': 'info'
  }
  return roleTypes[role || ''] || 'info'
}

// 获取用户角色标签
const getRoleLabel = (role: string | null) => {
  const roleLabels: Record<string, string> = {
    'SUPER_ADMIN': '超级管理员',
    'ADMIN': '管理员',
    'DEVELOPER': '开发者',
    'VIEWER': '查看者'
  }
  return roleLabels[role || ''] || '未知角色'
}

// 格式化日期时间
// 使用统一的日期时间格式化函数

// 加载统计数据
const loadStatistics = async () => {
  loading.value = true
  try {
    // 使用单次请求获取所有统计数据
    const response = await statsService.getSystemStats()
    const data = response.data

    // 动态更新所有统计数据
    Object.keys(data!).forEach(key => {
      if (typeof (data as any)[key] === 'number') {
        (stats as any)[key] = (data as any)[key]
      }
    })

    // 更新最后更新时间
    if (data?.lastUpdate) {
      lastUpdate.value = new Date(data.lastUpdate)
    }

  } catch (error) {
    console.error('Load statistics error:', error)
    MessageService.error('加载统计数据失败')

    // 错误时设置默认值
    statisticsItems.value.forEach(item => {
      stats[item.key] = 0
    })
    lastUpdate.value = new Date()
  } finally {
    loading.value = false
  }
}

// 页面初始化
onMounted(() => {
  loadStatistics()
})
</script>

<style scoped>
/* ===== 首页特有样式 ===== */

/* 页面居中布局 */
.home-view {
  max-width: 1400px;
  margin: 0 auto;
}

/* 页面头部居中 */
.home-view .page-header__content {
  text-align: center;
}

/* 快速访问区域 */
.quick-access-section {
  margin-bottom: var(--dbu-space-8);
}

.quick-links {
  display: flex;
  gap: var(--dbu-space-4);
  flex-wrap: wrap;
  justify-content: center;
}

.quick-link {
  text-decoration: none;
  transition: all var(--dbu-transition-normal);
}

.quick-link:hover {
  transform: translateY(-1px);
}

.quick-link .el-button {
  display: flex;
  align-items: center;
  gap: var(--dbu-space-2);
  min-width: 120px;
  justify-content: center;
}

/* 系统概览区域 */
.system-overview-section {
  margin-bottom: var(--dbu-space-8);
}

.overview-content {
  padding: var(--dbu-space-4) 0;
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h3 {
  margin: 0;
  font-size: var(--dbu-text-lg);
  font-weight: 600;
  color: var(--dbu-gray-800);
}

/* 统计卡片扩展样式 */
.home-view .stat-card:hover {
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .home-view {
    max-width: 100%;
  }
}

@media (max-width: 768px) {
  .home-view .page-header__content {
    text-align: left;
  }

  .quick-links {
    flex-direction: column;
    align-items: stretch;
  }

  .quick-link .el-button {
    width: 100%;
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .quick-links {
    gap: var(--dbu-space-3);
  }

  .quick-link .el-button {
    min-width: auto;
    padding: var(--dbu-space-2) var(--dbu-space-4);
    font-size: var(--dbu-text-sm);
  }
}
</style>